package initconf

import (
	"fmt"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var DB *gorm.DB

func InitMysql() {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local&timeout=%s",
		Conf.MySQLConfig.User,
		Conf.MySQLConfig.Password,
		Conf.MySQLConfig.Host,
		Conf.MySQLConfig.Port,
		Conf.MySQLConfig.DBName,
		Conf.MySQLConfig.Timeout)
	// Open 连接
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		panic("failed to connect mysql.")
	}
	DB = db
	setPool(DB)
}

func setPool(db *gorm.DB) {
	sqldb, err := db.DB()
	if err != nil {
		panic("sql db error")
	}
	sqldb.SetMaxIdleConns(20)
	sqldb.SetMaxOpenConns(20)
	sqldb.SetConnMaxLifetime(time.Hour)
}
